package com.unione.unione_network.tcp_socket

import android.util.Log
import com.unione.unione_network.tcp_socket.bean.MsgType
import com.unione.unione_network.tcp_socket.bean.TcpMsg
import okio.IOException
import java.io.InputStream

/**
 * 特定字符的粘包处理,首尾各一个Byte[],不可以同时为空，如果其中一个为空，那么以不为空的作为分割标记
 * 例：协议制定为  ^+数据+$，首就是^，尾是$
 */
class AGVStickPackageHelper(private val head: ByteArray, private val tail: ByteArray) :
    AbsStickPackageHelper {

    private var bytes: MutableList<Byte> = mutableListOf()
    private var remainingBytes: ByteArray? = null

    companion object {
        const val TAG = "AGVStickPackageHelper"
    }

    override fun execute(inputStream: InputStream): ByteArray? {
        val buffer = ByteArray(1024)
        var bytesRead = inputStream.read(buffer)
        if (bytesRead == -1) {
            bytesRead = 0
            if (remainingBytes == null || remainingBytes!!.isEmpty()) {
                return null
            }
        }
        val totalBytes = when (remainingBytes) {
            null -> buffer.copyOfRange(0, bytesRead)
            else -> {
                val combined = ByteArray(remainingBytes!!.size + bytesRead)
                System.arraycopy(
                    remainingBytes,
                    0,
                    combined,
                    0,
                    remainingBytes!!.size
                )
                if (bytesRead != 0) {
                    System.arraycopy(
                        buffer,
                        0,
                        combined,
                        remainingBytes!!.size,
                        bytesRead
                    )
                }
                combined
            }
        }
        val sigByte = '\r'.code.toByte()
        when (val index = totalBytes.indexOfFirst { it == sigByte }) {
            -1 -> {
                // 此时意味着数据太大 要等下一个buffer
                remainingBytes = totalBytes.copyOf()
            }

            0 -> {
                //两种情况/r/n 或者/r/n/r/n
                remainingBytes = if (totalBytes[2] == sigByte) {
                    totalBytes.copyOfRange(4, totalBytes.size)
                } else {
                    totalBytes.copyOfRange(2, totalBytes.size)
                }
            }

            1 -> {
                remainingBytes = totalBytes.copyOfRange(3, totalBytes.size)
            }

            else -> {
                val message = totalBytes.copyOfRange(0, index)
//                val messageStr =
//                    String(message).replace("\\r", "").replace("\\n", "")
//                val tcpMsg = TcpMsg().apply {
//                    sourceDataBytes =
//                        messageStr.toByteArray(mTcpConnConfig.charsetName)
//                    target = mTargetInfo
//                    msgType = MsgType.Receive
//                    sourceDataString = messageStr
//                }
//                tcpMsg.setTime()
//                //  Log.d(TAG, "tcp Receive  succ msg= ${tcpMsg.sourceDataString}")
//                notifyReceive(tcpMsg) //notify listener
                remainingBytes = totalBytes.copyOfRange(index, totalBytes.size)
                return message
            }
        }
        return ByteArray(0)
    }

    private fun getRangeBytes(bytes: MutableList<Byte>, start: Int, end: Int): ByteArray {
        return bytes.subList(start, end).map(Byte::toByte).toByteArray()
    }


//    private fun endWith(src: ByteArray, target: ByteArray): Boolean {
//        if (src.size < target.size || target.isEmpty()) {
//            return false
//        }
//        for (i in target.indices) { //逆序比较
//            if (target[target.size - i - 1] != src[src.size - i - 1]) {
//                return false
//            }
//        }
//        return true
//    }

    private fun endWith(src: ByteArray, target: ByteArray): Boolean {
        if (src.size < target.size || target.isEmpty()) {
            return false
        }
        if (String(src, Charsets.UTF_8).endsWith(String(target, Charsets.UTF_8))) {
            return true
        }
        return false
    }
}